package com.mk.cloud.common.controller;

import act.Act;
import act.controller.Controller;
import com.mk.cloud.common.domain.CpConfig;
import com.mk.cloud.common.enums.ConfigCode;
import com.mk.cloud.common.interceptor.ITransacte;
import com.mk.cloud.common.interceptor.cookie.CookieService;
import com.mk.cloud.common.interceptor.cookie.ICLogin;
import org.osgl.util.S;import com.mk.cloud.common.util.S2;
import org.osgl.$;
import org.osgl.mvc.annotation.GetAction;
import org.osgl.mvc.annotation.PostAction;
import org.osgl.mvc.annotation.With;
import org.osgl.mvc.result.Result;

import javax.inject.Inject;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@SuppressWarnings("unused")
@Controller("cfg")
public class CpConfigController extends CookieService {
    @Inject
    private CpConfig.Mapper cpConfigMapper;

    @GetAction("index.json")
    @With(ICLogin.class)
    public Result index() {
        List<CpConfig> configs = new ArrayList<>();
        int i = 0, j = ConfigCode.values().length;
        while (i < j) {
            configs.add(ConfigCode.values()[i++].convertConfig(me.getCoid()));
        }
        return renderJson(configs);
    }

    @With({ICLogin.class, ITransacte.class})
    @PostAction("save.json")
    public String save(String key,String value) {
        CpConfig config = new CpConfig();
        config.setCfid(key);
        String coid = "";
        if(S.isNotBlank(me.getCoid())){
            coid = me.getCoid();
        }
        config.setCoid(coid);
        CpConfig cpConfig = cpConfigMapper.single(config);
        if ($.isNull(cpConfig)) {
            cpConfig = new CpConfig();
            cpConfig.setCfid(key);
            cpConfig.setCfvalue(value);
            cpConfig.setCoid(coid);
            cpConfigMapper.insert(cpConfig);
        } else {
            cpConfig.setCfvalue(value);
            cpConfigMapper.updateTemplateById(cpConfig);
        }
        return "0";
    }

}


